<template>
    <div>
        <h1>IOT Portal</h1>

        <p><input type="text" v-model="sendMessage">{{sendMessage}}</p>
        <p><button @click.prevent="send">发送</button>{{receivedMessage}}</p>
    </div>
</template>

<script>
var socket;
var uri = "ws://" + window.location.host + "/ws";


export default {
    data() {
        return {
            message: '',
            sendMessage: '',
            receivedMessage: ''
        }
    },
    methods: {
        send(){
            this.receivedMessage = '';
            this.$socket.send(this.sendMessage);
        },
        recived(e){
            this.receivedMessage = "Received: "+e.data;
        }
    },
    socket: {
        events:{
            connect(){
                console.log("Websocket connected to " + this.$socket.nsp);
            },
            message(msg){
                this.receivedMessage = msg;
            },
            disconnect() {
                console.log("Websocket disconnected from " + this.$socket.nsp);
            },

            error(err) {
                console.error("Websocket error!", err);
            }
        }
    },
    created(){
        this.$socket = new WebSocket(uri);
        this.$socket.onmessage = this.recived;
    }
}
</script>